/**
 * 公共导航JavaScript库
 * 包含导航相关的功能
 */

// 生成导航HTML
function generateNavigation(currentPage = '') {
    const navItems = [
        { href: '/', text: '新闻中心', class: 'news', id: 'news' },
        { 
            href: '#', 
            text: '每日复盘', 
            class: 'daily-review', 
            id: 'daily-review',
            submenu: [
                { href: '/limit_up_analysis', text: '涨停分析', class: 'limit-up', id: 'limit-up' },
                { href: '/consecutive_limit_up', text: '连板梯队', class: 'consecutive', id: 'consecutive' },

            ]
        },
        { href: '/performance', text: '收益分析', class: 'performance', id: 'performance' },
        { href: '/fundamental', text: '基本面信息', class: 'fundamental', id: 'fundamental' }
    ];
    
    let navHtml = '<div class="header-nav-links">';
    
    navItems.forEach(item => {
        const isActive = currentPage === item.id ? ' active' : '';
        const hasSubmenu = item.submenu ? ' has-submenu' : '';
        
        navHtml += `
            <div class="nav-item${hasSubmenu}">
                <a href="${item.href}" class="header-nav-link ${item.class}${isActive}${hasSubmenu}">
                    <i class="fas fa-${getIconForPage(item.id)}"></i>
                    ${item.text}
                    ${item.submenu ? '<i class="fas fa-chevron-down submenu-arrow"></i>' : ''}
                </a>
                ${item.submenu ? generateSubmenu(item.submenu, currentPage) : ''}
            </div>
        `;
    });
    
    navHtml += '</div>';
    return navHtml;
}

// 生成子菜单HTML
function generateSubmenu(submenuItems, currentPage) {
    let submenuHtml = '<div class="submenu">';
    
    submenuItems.forEach(item => {
        const isActive = currentPage === item.id ? ' active' : '';
        submenuHtml += `
            <a href="${item.href}" class="submenu-link ${item.class}${isActive}">
                <i class="fas fa-${getIconForPage(item.id)}"></i>
                ${item.text}
            </a>
        `;
    });
    
    submenuHtml += '</div>';
    return submenuHtml;
}

// 根据页面ID获取对应的图标
function getIconForPage(pageId) {
    const iconMap = {
        'news': 'newspaper',
        'daily-review': 'calendar-day',
        'limit-up': 'chart-line',
        'consecutive': 'fire',

        'performance': 'chart-bar',
        'fundamental': 'clipboard-list'
    };
    return iconMap[pageId] || 'circle';
}

// 初始化导航
function initNavigation(currentPage = '') {
    const navContainer = document.querySelector('.header-nav-links');
    if (navContainer) {
        navContainer.innerHTML = generateNavigation(currentPage);
    }
}

// 设置当前页面为激活状态
function setActiveNavigation(pageId) {
    // 移除所有激活状态
    document.querySelectorAll('.header-nav-link, .submenu-link').forEach(link => {
        link.classList.remove('active');
    });
    
    // 设置当前页面为激活状态
    const activeLink = document.querySelector(`.header-nav-link.${pageId}, .submenu-link.${pageId}`);
    if (activeLink) {
        activeLink.classList.add('active');
        
        // 如果是子菜单项，也要激活父菜单
        if (activeLink.classList.contains('submenu-link')) {
            const parentNavItem = activeLink.closest('.nav-item');
            const parentLink = parentNavItem.querySelector('.header-nav-link');
            if (parentLink) {
                parentLink.classList.add('active');
            }
        }
    }
}

// 导航点击事件处理
function handleNavigationClick(event) {
    const link = event.currentTarget;
    const href = link.getAttribute('href');
    
    // 如果是当前页面，阻止默认行为
    if (window.location.pathname === href) {
        event.preventDefault();
        return;
    }
    
    // 添加加载状态
    link.classList.add('loading');
    
    // 延迟移除加载状态（页面跳转后会自动移除）
    setTimeout(() => {
        link.classList.remove('loading');
    }, 1000);
}

// 子菜单点击事件处理
function handleSubmenuClick(event) {
    const link = event.currentTarget;
    const href = link.getAttribute('href');
    
    // 如果是当前页面，阻止默认行为
    if (window.location.pathname === href) {
        event.preventDefault();
        return;
    }
    
    // 添加加载状态
    link.classList.add('loading');
    
    // 延迟移除加载状态（页面跳转后会自动移除）
    setTimeout(() => {
        link.classList.remove('loading');
    }, 1000);
}

// 初始化导航事件监听
function initNavigationEvents() {
    // 主导航链接事件
    document.querySelectorAll('.header-nav-link').forEach(link => {
        link.addEventListener('click', handleNavigationClick);
    });
    
    // 子菜单链接事件
    document.querySelectorAll('.submenu-link').forEach(link => {
        link.addEventListener('click', handleSubmenuClick);
    });
}

// 初始化子菜单交互
function initSubmenuInteraction() {
    // 鼠标悬停显示子菜单
    document.querySelectorAll('.nav-item.has-submenu').forEach(navItem => {
        const link = navItem.querySelector('.header-nav-link');
        const submenu = navItem.querySelector('.submenu');
        
        if (link && submenu) {
            // 鼠标进入显示子菜单
            navItem.addEventListener('mouseenter', () => {
                submenu.style.display = 'block';
                link.classList.add('submenu-open');
            });
            
            // 鼠标离开隐藏子菜单
            navItem.addEventListener('mouseleave', () => {
                submenu.style.display = 'none';
                link.classList.remove('submenu-open');
            });
            
            // 点击切换子菜单（移动端）
            link.addEventListener('click', (e) => {
                if (window.innerWidth <= 768) {
                    e.preventDefault();
                    const isOpen = submenu.style.display === 'block';
                    submenu.style.display = isOpen ? 'none' : 'block';
                    link.classList.toggle('submenu-open', !isOpen);
                }
            });
        }
    });
}

// 响应式导航处理
function initResponsiveNavigation() {
    const mobileMenuToggle = document.querySelector('.mobile-menu-toggle');
    const navLinks = document.querySelector('.header-nav-links');
    
    if (mobileMenuToggle && navLinks) {
        mobileMenuToggle.addEventListener('click', () => {
            navLinks.classList.toggle('mobile-open');
        });
        
        // 点击导航链接后关闭移动端菜单
        navLinks.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', () => {
                navLinks.classList.remove('mobile-open');
            });
        });
    }
}

// 页面加载完成后自动初始化导航
document.addEventListener('DOMContentLoaded', () => {
    // 根据当前页面路径设置激活状态
    const currentPath = window.location.pathname;
    let currentPage = '';
    
    if (currentPath === '/' || currentPath === '/news') {
        currentPage = 'news';
    } else if (currentPath === '/limit_up_analysis') {
        currentPage = 'limit-up';
    } else if (currentPath === '/consecutive_limit_up') {
        currentPage = 'consecutive';
    
    } else if (currentPath === '/performance') {
        currentPage = 'performance';
    } else if (currentPath === '/fundamental') {
        currentPage = 'fundamental';
    }
    
    // 初始化导航并生成HTML
    initNavigation(currentPage);
    setActiveNavigation(currentPage);
    initNavigationEvents();
    initSubmenuInteraction();
    initResponsiveNavigation();
});
